// packageC/selfCarry/selfCarryApply/selfCarryApply.js
var app = getApp();
var location = require("../../../mybehaviors/location/location");

// var WxParse = require('../../../wxParse/wxParse.js');
Page({
  behaviors: [location],

  /**
   * 页面的初始数据
   */
  data: {
    msgText: 0,
    showtips: true,
    swlist: [],
    swlis: [],
    shenqShow: false,
    is_hotel: false,
    uploadUrl: "",
    o2o_status: 1,
    //定位信息
    address: "",
    point: {
      lat: "",
      lng: "",
    },
    city: "",
    title: "",
    noIs: true,
    bor: true,
    showDel: false,
    apply: {
      password: "",
      realname: "",
      mobile: "",
      //store名字
      deliver_name: "",
      lng: "",
      lat: "",
      business_hours_start: "00:00",
      business_hours_end: "00:00",
      //省市区 街道id
      province_id: "",
      city_id: "",
      district_id: "",
      street_id: "",
      address: "",
      //资质图片src
      aptitute: [],
      remark: "",
      id_card_front: "",
      id_card_side: "",
    },
    categoryName: "",
    strShow: false,
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    districtVal: [],
    streetShow: false,
    addressShow: false,
    addressName: "",
    provice: "",
    beginTimeshow: false,
    endTimeshow: false,
    imageUrl: "",
    hotelTitleType: "",
    levelShow: false,
    applyOptionInfo: {},
    apply_switch: false, //判断子平台角色时账号密码不填 - #11419
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData();
    wx.setNavigationBarTitle({
      title: "申请",
    });
    this.setData({
      uploadUrl: "upload.uploadPic",
    });

    //加载地址数据初始化
    this._initAddressInfo();
    this.getData();
    try {
      let ztd_temporary = wx.getStorageSync('ztd_temporary')||null;
      if(ztd_temporary){
        this.setData({
          apply: ztd_temporary
        });
      }
    } catch (error) {
      console.log(error);
    }

    this._getLocation((mapdata, e) => {
      this.setData({
        "apply.lng": e.lng,
        "apply.lat": e.lat,
        mapdata_address: mapdata.address,
      });
    });
    
    let basic_info = wx.getStorageSync("yz_basic_info");
    this.setData({
      apply_switch: basic_info.plugin_setting.sub_platform?.apply_switch ?? false
    })
  },
  goloc(){
    wx.setStorageSync("ztd_temporary", this.data.apply);
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=selfCarryApply',
    });
  },
  showdel(e) {
    console.log(e);
    this.setData({
      showDel: true,
    });
  },
  delIntu(e) {
    var delpaths = this.data.showpaths;
    // let del = e.currentTarget.id;
    // var indelpaths = delpaths.splice(del, 1);
    this.setData({
      showpaths: delpaths,
    });
  },
  delIntu_2(e) {
    var delpaths = this.data.showpaths_two;
    // let del = e.currentTarget.id;
    // var indelpaths = delpaths.splice(del, 1);
    this.setData({
      showpaths_two: delpaths,
    });
  },
  shenqShow() {
    this.setData({
      shenqShow: true,
    });
  },
  onClicksQ() {
    this.setData({
      shenqShow: false,
    });
  },
  callKf() {
    console.log("联系客服");
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    try {
      let value = wx.getStorageSync('applyaddresspoint');
      if (value) {
        this.setData({
          "apply.lng": value.point.lng,
          "apply.lat": value.point.lat,
          mapdata_address: value.address,
        });
      }
    } catch (e) {
      console.log(e);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  initData() {
    this.setData({
      showtips: true,
      msgText: 0,
      o2o_status: 1,
      // fileList2: [],
      "apply.username": "",
      "apply.password": "",
      "apply.realname": "",
      "apply.mobile": "",
      "apply.deliver_name": "",
      "apply.lng": "",
      "apply.lat": "",

      "apply.province_id": "",
      "apply.city_id": "",
      "apply.district_id": "",
      "apply.street_id": "",
      "apply.aptitute": [],
      "apply.remark": "",
      agreementChoose: false,
    });
  },
  //获取数据
  getData() {
    let that = this;
    let urlStr = "";
    urlStr += app.getNetAddresss(
      "plugin.package-deliver.frontend.apply.verify"
    );
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            o2o_status: 1,
            applyOptionInfo: res.data
          });
          wx.setNavigationBarTitle({
            title: res.data.name + "申请",
          });
          if (app._isTextEmpty(res.data.cservice)) {
            that.setData({
              cservice: false,
            });
          } else {
            that.setData({
              cservice: true,
            });
          }
          // let article = that.data.o2o_info;
          /**
           * WxParse.wxParse(bindName , type, data, target,imagePadding)
           * 1.bindName绑定的数据名(必填)
           * 2.type可以为html或者md(必填)
           * 3.data为传入的具体数据(必填)
           * 4.target为Page对象,一般为this(必填)
           * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
           */
          // WxParse.wxParse('article', 'html', article, that);
        } else {
          that.setData({
            o2o_status: 2,
          });
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  usernameinp(e) {
    let val = e.detail.value;
    this.setData({
      "apply.username": val,
    });
  },
  passwordinp(e) {
    let val = e.detail;
    this.setData({
      "apply.password": val,
    });
    this.msgText = this.checkStrong(val);
    if (this.msgText == 3) {
      this.setData({
        showtips: false,
      });
    } else {
      this.setData({
        showtips: true,
      });
    }
  },
  checkStrong(sValue) {
    var modes = 0;
    //正则表达式验证符合要求的
    if (sValue.length < 1) return modes;
    if (/\d/.test(sValue)) modes++; //数字
    if (/[a-z]/.test(sValue)) modes++; //小写
    if (/[A-Z]/.test(sValue)) modes++; //大写
    // if (/\W/.test(sValue)) modes++; //特殊字符

    //逻辑处理
    switch (modes) {
    case 1:
      return 1;
    case 2:
      return 2;
    case 3:
      return sValue.length < 8 ? 2 : 3;
    }
    return modes;
  },
  realnameinp(e) {
    let val = e.detail.value;
    this.setData({
      "apply.realname": val,
    });
  },
  mobileinp(e) {
    let val = e.detail.value;
    this.setData({
      "apply.mobile": val,
    });
  },
  storeNameinp(e) {
    let val = e.detail.value;
    this.setData({
      "apply.deliver_name": val,
    });
  },
  showCategory() {
    this.setData({
      categoryShow: true,
    });
  },
  onClickLeft() {
    this.setData({
      categoryShow: false,
    });
  },
  chooseCategory(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      categoryName: item.name,
      "apply.categoryId": item.id,
      categoryShow: false,
    });
  },
  addressShowbtn() {
    this.setData({
      addressShow: true,
    });
  },
  //所在地选择显示
  showAddBtn(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].showAdd"]: true,
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      addressShow: false,
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name":
            res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0],
        });
        that._getCityData();
      },
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    console.log("城市", "_data", _data);
    var that = this;
    var _keyName = "cityData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json,
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1],
        });
        that._getDistrictData();
      },
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    console.log("地区", "_data", _data);
    console.log(_data);
    var that = this;
    var _keyName = "districtData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json,
        });
        console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2],
        });
        console.log("over", that.data.selectAddressData);
      },
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },
  //城市结果
  resultAdd: function () {
    let seleData = this.data.selectAddressData;
    let retCity =
      seleData[0].name + " " + seleData[1].name + " " + seleData[2].name;
    this.setData({
      addressName: retCity,
      provice: seleData[0].name,
      city: seleData[1].name,
      district: seleData[2].name,
    });
    this.setData({
      "apply.province_id": seleData[0].id,
      "apply.city_id": seleData[1].id,
      "apply.district_id": seleData[2].id,
      addressShow: false,
    });
    this.getStreet(seleData[2].id);
  },
  //获取街道
  getStreet(param) {
    let that = this;
    let urlStr = "";
    urlStr += app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              strShow: true,
            });
          } else {
            that.setData({
              strShow: false,
            });
          }
        } else {
          that.setData({
            strShow: false,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  streetShowbtn() {
    this.setData({
      streetShow: true,
    });
  },
  treetShowLeft() {
    this.setData({
      streetShow: false,
    });
  },
  streetConfirm(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      street: item.areaname,
      "apply.street_id": item.id,
      streetShow: false,
    });
  },
  addressinp(e) {
    let val = e.detail.value;
    this.setData({
      "apply.address": val,
    });
  },
  // business_hours_startbtn() {
  // 	this.setData({
  // 		business_hours_startshow: true
  // 	})
  // },
  // business_hours_startClose() {
  // 	this.setData({
  // 		business_hours_startshow: false
  // 	})
  // },
  endTimebtn() {
    this.setData({
      endTimeshow: true,
    });
  },
  endTimeClose() {
    this.setData({
      endTimeshow: false,
    });
  },
  beginTimemessage(e) {
    let time = e.detail.value;
    this.setData({
      "apply.business_hours_start": time,
    });
    // business_hours_startshow: false
  },
  endTimemessage(e) {
    let time = e.detail.value;
    this.setData({
      "apply.business_hours_end": time,
    });
    // business_hours_endshow: false
  },

  // 其他图片
  onRead_6() {
    let that = this;
    // let urlStr = app.getNetAddresss(this.data.uploadUrl);
    let ig = "2";
    wx.chooseImage({
      count: 9,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        // var tempFilePaths = res.tempFilePaths
        that.unload(
          {
            tempFilePaths: res.tempFilePaths,
          },
          ig
        );
      },
    });
  },
  //多张上传方法
  unload(data, ig) {
    console.log(ig);
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: urlStr,
      filePath: data.tempFilePaths[i],
      name: "file",
      formData: null,
      success(resdata) {
        var res = JSON.parse(resdata.data);
        console.log(res.data.img_url);
        that.data.swlis.push(res.data.img_url);
        that.setData({
          showpaths_two: that.data.swlis,
          "apply.thumb": that.data.swlis,
        });
        console.log(that.data.apply);
      },
      fail(e) {
        fail++;
      },
      complete(e) {
        i++;
        if (i == data.tempFilePaths.length) {
          //当图片传完时，停止调用
          console.log("执行完毕");
          console.log("成功：" + success + " 失败：" + fail);
        } else {
          //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.unload(data, ig); //递归，回调自己
        }
      },
    });
  },
  onRead_3() {
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        // wx.compressImage({
        // 	src: tempFilePaths[0], // 图片路径
        // 	quality: 60, // 压缩质量
        // 	success(e) {
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            var res = JSON.parse(resdata.data);
            if (res.result == 1) {
              that.setData({
                fileList3: res.data.img_url,
                "apply.aptitute": [res.data.img_url],
              });
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
            }
          },
        });
        // 	},
        // 	fail(e) {

        // 	},
        // 	complete(e) {

        // 	}
        // })
      },
    });
  },
  onRead_4() {
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        // wx.compressImage({
        // 	src: tempFilePaths[0], // 图片路径
        // 	quality: 60, // 压缩质量
        // 	success(e) {
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            var res = JSON.parse(resdata.data);
            if (res.result == 1) {
              that.setData({
                fileList4: photourl,
                "apply.id_card_front": res.data.img_url,
              });
              console.log(that.data.apply.id_card_front);
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
            }
          },
        });
        // },
        // fail(e) {

        // },
        // complete(e) {

        // }
        // })
      },
    });
  },
  onRead_5() {
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        // wx.compressImage({
        // 	src: tempFilePaths[0], // 图片路径
        // 	quality: 60, // 压缩质量
        // 	success(e) {
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            var res = JSON.parse(resdata.data);
            if (res.result == 1) {
              that.setData({
                fileList5: res.data.img_url,
                "apply.id_card_side": res.data.img_url,
              });
              console.log(that.data.apply);
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
            }
          },
        });
      },
      // fail(e) {

      // 		},
      // 		complete(e) {

      // 		}
      // 	})
      // }
    });
  },
  remarkinp(e) {
    let val = e.detail.value;
    console.log(val);
    this.setData({
      "apply.remark": val,
    });
  },
  storeIn(e) {
    console.log(e.detail.value);
    let val = e.detail.value;
    this.setData({
      "apply.storeIntroduce": val,
    });
  },
  Chooseinp(e) {
    let Bol = e.detail;
    this.setData({
      agreementChoose: Bol,
    });
  },
  removeImg: function (e) {
    let index = e.currentTarget.dataset.index;
    let aptitute = this.data.apply.aptitute;
    let fileList2 = this.data.fileList2;
    aptitute.splice(index, 1);
    fileList2.splice(index, 1);
    this.setData({
      "apply.aptitute": aptitute,
      fileList2: fileList2,
    });
  },
  //提交数据
  setApplyData() {
    console.log(this.data.apply);
    if (app._isTextEmpty(this.data.apply.username) && !this.data.apply_switch) {
      wx.showToast({
        icon: "none",
        title: "请填写账号",
        duration: 1500,
      });
      return;
    }
    if (app._isTextEmpty(this.data.apply.password) && !this.data.apply_switch) {
      wx.showToast({
        icon: "none",
        title: "请填写密码",
        duration: 1500,
      });
      return;
    }

    if (this.data.msgText != 3 && this.data.applyOptionInfo.safe == 1) {
      wx.showToast({
        icon: "none",
        title: "请正确填写密码",
        duration: 1500,
      });
      return;
    }

    if (app._isTextEmpty(this.data.apply.realname)) {
      wx.showToast({
        icon: "none",
        title: "请填写真实姓名",
        duration: 1500,
      });
      return;
    }

    if (app._isTextEmpty(this.data.apply.mobile)) {
      wx.showToast({
        icon: "none",
        title: "请填写手机号码",
        duration: 1500,
      });
      return;
    }

    if (app._isMoblie(this.data.apply.mobile)) {
      wx.showToast({
        icon: "none",
        title: "请输入正确的手机号",
        duration: 1500,
      });
      return;
    }

    if (app._isTextEmpty(this.data.apply.deliver_name)) {
      wx.showToast({
        icon: "none",
        title: "请填写提货点名称",
        duration: 1500,
      });
      return;
    }

    if (
      app._isTextEmpty(this.data.apply.province_id) ||
      app._isTextEmpty(this.data.apply.city_id) ||
      app._isTextEmpty(this.data.apply.district_id)
    ) {
      wx.showToast({
        icon: "none",
        title: "请选择省市区",
        duration: 1500,
      });
      return;
    }

    if (app._isTextEmpty(this.data.apply.street_id)) {
      wx.showToast({
        icon: "none",
        title: "请选择街道",
        duration: 1500,
      });
      return;
    }

    if (app._isTextEmpty(this.data.apply.address)) {
      wx.showToast({
        icon: "none",
        title: "请填写详细地址",
        duration: 1500,
      });
      return;
    }

    if (
      app._isTextEmpty(this.data.apply.lng) ||
      app._isTextEmpty(this.data.apply.lat)
    ) {
      wx.showToast({
        icon: "none",
        title: "经纬度不能为空",
        duration: 1500,
      });
      return;
    }

    if (
      app._isTextEmpty(this.data.apply.business_hours_start) ||
      app._isTextEmpty(this.data.apply.business_hours_end)
    ) {
      wx.showToast({
        icon: "none",
        title: "营业开始时间活营业结束时间不能为空",
        duration: 1500,
      });
      return;
    }

    if (this.data.applyOptionInfo.is_license && app._isTextEmpty(this.data.apply.aptitute)) {
      wx.showToast({
        icon: "none",
        title: "请上传营业执照",
        duration: 1500,
      });
      return;
    }
    if (this.data.applyOptionInfo.is_photo && app._isTextEmpty(this.data.apply.thumb)) {
      wx.showToast({
        icon: "none",
        title: `请上传${this.data.applyOptionInfo.name}图片`,
        duration: 1500,
      });
      return;
    }

    if (!this.data.agreementChoose) {
      wx.showToast({
        icon: "none",
        title: "请同意申请协议",
        duration: 1500,
      });
      return;
    }

    let that = this;
    let json = {
      apply: this.data.apply,
    };
    let urlStr = "";

    urlStr = app.getNetAddresss("plugin.package-deliver.frontend.apply.store");

    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          try {
            //  每次关闭要清除存储
            wx.removeStorageSync("ztd_temporary");
          } catch (e) {
            // Do something when catch error
          }
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                that.goHome();
              }, 1500); //延迟时间
            },
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
      fail: function (res) {},
    });
  },
  //去商城
  goHome() {
    wx.reLaunch({
      url: "/packageG/index/index",
    });
  },
  levelShowbtn() {
    this.setData({
      levelShow: true,
    });
  },
  levelShowLeft() {
    this.setData({
      levelShow: false,
    });
  },
  chooseStarLevel(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      "apply.starRated": item.value,
      levelShow: false,
      levelName: item.name,
    });
  },
});
